package com.kasuroid.core;

import java.util.HashMap;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Manages the textures available in the framework.
 * @author Tomasz Rusak
 */
public class TextureManager implements Module
{
    private final String mName = "TextureManager"; 

    private HashMap<Integer, Texture> mTexturesPool;

    public TextureManager() {}

    public int init()
    {
        mTexturesPool = new HashMap<Integer, Texture>();
        Debug.inf(getClass().getName(), getName() + " initialized");
        return RetCode.SUCCESS;
    }

    public int term()
    {
        mTexturesPool.clear();
        Debug.inf(getClass().getName(), getName() + " terminated");
        return RetCode.SUCCESS;
    }

    /**
     * Loads the texture from the resources and caches it into mTexturesPool.
     * @param pathId Id of the bitmap resource to load.
     * @return Loaded texture or null if error.
     */
    public Texture load(int pathId)
    {
        Texture texture = null;

        // Check if the texture is already loaded.
        texture = mTexturesPool.get(pathId);
        if (texture == null)
        {
            Resources res = Core.getInstance().getContext().getResources();
            Bitmap bitmap = BitmapFactory.decodeResource(res, pathId);
            if (bitmap != null)
            {
                texture = new Texture(bitmap);
                mTexturesPool.put(pathId, texture);
            }
        }
 
        return texture;
    }

    public String getName()
    {
        return mName;
    }
}